<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" :title="title" custom-class="mydialog"
    width="50%" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="130px" size="small">

      <el-form-item :label="trading ?  '配送商名称' :'代理名称'">
        {{ trading ? openForm.distributeName : openForm.agentName }}
      </el-form-item>

      <el-form-item label="产品选择" prop="productId">
        <el-select v-model="openForm.productId" placeholder="请选择产品" style="width: 100%" @change="handlChangeProduct">
          <el-option v-for="item in procuctLists" :key=" trading ?item.productId : item.id"
            :label="getProductName(item)" :value="trading ?item.productId : item.id" />
        </el-select>
      </el-form-item>

      <el-form-item :label="trading ?  '配送日期' :'销售日期'"  prop="directionTime">
        <date-picker v-model:date="openForm.directionTime" :disabled-date="disabledDate" placeholder="请选择日期"
          style="width: 100%" type="date" />
      </el-form-item>

      <el-form-item label="配送数量" prop="directionNumber">
        <el-input v-model="openForm.directionNumber" clearable placeholder="配送数量">
          <template #append>
            <span>{{ getLabel('sell_unit', openForm.minSaleUnit) }}</span>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="批号" prop="batchNumber">
        <el-input v-model="openForm.batchNumber" clearable placeholder="请输入批号" />
      </el-form-item>

      <el-form-item label="终端名称" prop="terminalName">
        <div style="display: flex;justify-content:space-between">
          <el-autocomplete v-model="openForm.terminalName" :fetch-suggestions="querySearchTerminal" :loading="false"
            placeholder="请输入终端名称" style="width: 70%" @select="handleSelecTerminal">
            <template #default="{ item }">
              <div class="distributeName">{{ item.terminalName }}</div>
            </template>
          </el-autocomplete>
          <div style="width: 25%;text-align:right">
            <span style="padding-right:20px ;">未找到终端</span>
            <el-button type="text" @click="handleCreateTerminal">创建终端</el-button>
          </div>
        </div>

      </el-form-item>

      <el-form-item v-if="trading && (openForm?.itemTitle === null)" label="进货关系" prop="stanInfoId">
        <table-view :cell-style="cellStyle" :data="tableTerminaData" border header-cell-class-name="table-header"
          size="medium" @row-click="aloneClick">
          <el-table-column :show-overflow-tooltip="true" align="center" width="50">
            <template #default="{row}">
              <el-radio v-model="openForm.stanInfoId" :label="row.StanInfo.id" />
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="center" label="营销模式">
            <template #default="{row}">
              <span v-if="row.StanInfo?.sellMode !== 'direct'">
                <span v-if="row.StanInfo?.agentAttribute === '1'">区域招商</span>
                <span v-if="row.StanInfo?.agentAttribute === '2'">精细招商</span>
              </span>
              <span v-else> 终端直销</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" header-align="center" label="代理名称" width="180">
            <template #default="{row}">
              {{ row.StanInfo?.agentDetail?.agentName }}
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="center" label="交易价(元)">
            <template #default="{row}">
              {{ row.StanInfo.tradePrice }}元
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="center" label="终端价(元)">
            <template #default="{row}">
              {{ row.StanInfo.terminalPrice }}元
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="center" label="配送费(元)">

            <template #default="{row}">
              <div v-if="row?.DevDistributeInfo?.computeMode==='固定价格'">
                <span>{{ row?.DevDistributeInfo?.distributePrice }}元</span>
              </div>
              <div v-if="row?.DevDistributeInfo?.computeMode==='终端价百分比'">
                <span>{{ row?.DevDistributeInfo?.distributePrice }}%</span><span>终端价</span>
              </div>
            </template>

          </el-table-column>
        </table-view>
      </el-form-item>

      <el-form-item v-if="openForm?.itemTitle">
        <div>{{ openForm.itemTitle[0] }}</div>
      </el-form-item>

      <el-form-item v-if="openForm?.itemTitle">
        <div style="display:flex;justify-content:space-between;">
          <div style="width: 80%;line-height: 20px">{{ openForm.itemTitle[1] }}</div>
          <el-button v-if="openForm?.itemTitle.length > 2" class="btnss" style="width: 20%;line-height: 20px"
            type="text" @click="handleTo">去添加</el-button>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>
        <template v-if="trading === false || openForm.itemTitle === null">
          <el-button v-if="title === '添加流向数据'" class="border-btn" size="small" style="margin-right: 20px;"
            @click="handlSave">保存并添加
          </el-button>
          <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">保存</el-button>
        </template>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, inject, onMounted, reactive, toRefs } from "vue";

export default {
  name: "AddData",
  props: {
    trading: {
      type: Boolean,
      default: true,
    },
  },
  emits: ["succsess"],
  setup(props, context) {
    //* ************自定义效验**********

    const validateNum = (rule, value, callback) => {
      if (!/(^[1-9]\d*$)/.test(value)) {
        callback(new Error("配送数量格式不正确(应为正整数)"));
      } else {
        callback();
      }
    };

    const validateId = (rule, value, callback) => {
      if (
        value === undefined ||
        value === 0 ||
        data.tableTerminaData.length === 0
      ) {
        callback(new Error("请选择交易价"));
      } else {
        callback();
      }
    };

    const validateTermina = (rule, value, callback) => {
      if (data.openForm.directionTime === "") {
        callback(new Error("请先选择日期"));
      } else {
        if (value === "") {
          callback(new Error("请先选择终端"));
        } else {
          callback();
        }
      }
    };
    //* ********************************
    const api = inject("api");
    var data = reactive({
      openBoole: false,
      title: "添加流向数据",
      openForm: {
        productName: "",
        producer: "",
        productPopularName: "",
        approvalNumber: "",
        packSpecs: "",
        productId: null,
        terminalId: 0,
        provinceCode: "",
        cityCode: "",
        areaCode: "",
        directionNumber: null,
        directionTime: "",
        batchNumber: "",
        minSaleUnit: "",
        distributeId: 0,
        distributeName: "",
        terminalName: "",
        terminalType: "",
        distributeDetailId: null,
        distributeDetailName: "",
        agentType: "",
        agentAttribute: "",
        agentId: "",
        agentName: "",
        terminalPrice: "",
        tradePrice: "",
        distributePrice: "",
        computeMode: "",
        id: 0,
        stanInfoId: 0,
        itemTitle: null,
      },
      rules: {
        productId: [
          { required: true, message: "请选择产品", trigger: "change" },
        ],
        directionTime: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],
        terminalName: [
          { required: true, validator: validateTermina, trigger: "change" },
        ],
        directionNumber: [
          { required: true, validator: validateNum, trigger: "blur" },
        ],
        batchNumber: [
          { required: true, message: "请输入批号", trigger: "blur" },
        ],
        stanInfoId: [
          { required: true, validator: validateId, trigger: "change" },
        ],
      },
      openRef: null,
      procuctLists: [],
      tableTerminaData: [],
      results: [],
      toPath: "",
      toBoole: false,
    });
    const currentInstance = getCurrentInstance();

    const disabledDate = (date) => {
      // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
      return date.getTime() > Date.now() - 8.64e6;
    };

    const handlCurNum = (val) => {
      data.openForm.cureNum = Number(val);
    };

    const close = () => {
      data.openBoole = false;
      data.openForm.distributeName = "";
      data.openForm.distributeId = "";
      handlRemove();
    };

    const handlRemove = () => {
      data.openRef.clearValidate();
      data.openRef.resetFields();
      data.tableTerminaData = [];
    };

    const open = (val, obj) => {
      data.openForm = {
        productName: "",
        producer: "",
        productPopularName: "",
        approvalNumber: "",
        packSpecs: "",
        productId: null,
        terminalId: 0,
        directionNumber: null,
        directionTime: "",
        batchNumber: "",
        minSaleUnit: "",
        distributeId: 0,
        distributeName: "",
        terminalName: "",
        terminalType: "",
        distributeDetailId: null,
        distributeDetailName: "",
        agentType: "",
        agentAttribute: "",
        agentId: "",
        agentName: "",
        terminalPrice: "",
        tradePrice: "",
        distributePrice: "",
        computeMode: "",
        id: 0,
      };
      if (val && obj === null) {
        data.title = "添加流向数据";
        data.openForm.distributeName = val.distributeName;
        data.openForm.distributeId = val.distributeId;
        data.openForm.agentName = val.agentName;
        data.openForm.agentId = val.agentId;
        handlProduct();
      }
      if (val && obj) {
        data.title = "编辑流向数据";
        data.openForm = JSON.parse(JSON.stringify(obj));
        data.openForm.distributeName = val.distributeName;
        data.openForm.distributeId = val.distributeId;
        data.openForm.agentName = val.agentName;
        data.openForm.agentId = val.agentId;
        handlProduct();
        if (props.trading) {
          handleDownList();
        }
      }
      data.openBoole = true;
    };

    const handlProduct = () => {
      if (props.trading) {
        api.businessFlow
          .TBUSINESSFLOW_PRODUCT(data.openForm.distributeId)
          .then((res) => {
            if (res.code === 0) {
              data.procuctLists = res.data || [];
            }
          });
      } else {
        api.businessFlow
          .TBUSINESSFLOW_AGENT_PRODUCT(data.openForm.agentId, "")
          .then((res) => {
            if (res.code === 0) {
              data.procuctLists = res.data.agentProduct || [];
            }
          });
      }
    };

    const handlChangeProduct = (val) => {
      var a = {};
      if (props.trading) {
        a = data.procuctLists.find((b) => b.productId === val);
        data.openForm.minSaleUnit = a.sellUnit;
        data.openForm.productPopularName = a.productPopularName;
        data.openForm.producer = a.producer;
        data.openForm.productName = a.productName;
        data.openForm.approvalNumber = a.approvalNumber;
        data.openForm.packSpecs = a.packSpecs;
      } else {
        a = data.procuctLists.find((b) => b.id === val);
        data.openForm.minSaleUnit = a.sellUnit;
        data.openForm.productPopularName = a.productPopularName;
        data.openForm.producer = a.producer;
        data.openForm.productName = a.productName;
        data.openForm.approvalNumber = a.approvalNumber;
        data.openForm.packSpecs = a.packSpecs;
      }

      data.openForm.terminalName = "";
      data.openForm.terminalId = "";
      data.tableTerminaData = [];
    };

    const querySearchTerminal = async (queryString, cb) => {
      const val = {
        terminalName: queryString,
      };
      let results = [];
      if (
        data.openForm.directionTime !== null &&
        data.openForm.directionTime !== "" &&
        queryString !== ""
      ) {
        const res = await api.businessFlow.TBUSINESSFLOW_TERMINA(val);
        if (res.code === 0) {
          results = res.data.list || [];
        }
      }
      cb(results);
    };

    const handleSelecTerminal = (val) => {
      if (val) {
        data.openForm.terminalName = val?.terminalName;
        data.openForm.terminalId = val?.id;
        data.openForm.provinceCode = val?.provinceCode;
        data.openForm.cityCode = val?.cityCode;
        data.openForm.areaCode = val?.areaCode;
        data.openForm.terminalType = val?.terminalType;
        if (props.trading) {
          handleDownList();
        } else {
          data.toPath = "businessFlow";
        }
      }
    };

    const handleDownList = () => {
      var a = {
        productId: data.openForm.productId,
        directionTime: data.openForm.directionTime,
        distributeId: data.openForm.distributeId,
        terminalId: data.openForm.terminalId,
        provinceCode: data.openForm.provinceCode,
        cityCode: data.openForm.cityCode,
        areaCode: data.openForm.areaCode,
      };
      api.businessFlow.TBUSINESSFLOW_DOWNLIST(a).then((res) => {
        if (res.code === 0) {
          data.tableTerminaData = res.data.list[0].devInfos || [];
          data.openForm.itemTitle = null;
          if (
            data.tableTerminaData.length > 0 &&
            data.tableTerminaData.length === 1
          ) {
            data.openForm.stanInfoId = data.tableTerminaData[0].StanInfo?.id;
            aloneClick(data.tableTerminaData[0]);
          }
        } else {
          data.openForm.itemTitle = res.msg.split("@");
          if (data.openForm.itemTitle.length === 3) {
            data.toBoole = true;
          } else {
            data.toBoole = false;
          }
        }
      });
    };

    const handleCreateTerminal = () => {
      window.open(
        `#/baseInfo/baseInfoTerminal?type=direct`
      );
    };

    const aloneClick = (row, column, event) => {
      data.openForm.stanInfoId = row?.StanInfo?.id;
      data.openForm.terminalType = row?.StanInfo.terminalType;
      data.openForm.distributeDetailId =
        row?.DevDistributeInfo?.distributeDetailId;
      data.openForm.distributeDetailName =
        row?.DevDistributeInfo?.distributeDetailName;
      data.openForm.agentType = row?.StanInfo?.sellMode;
      data.openForm.agentAttribute = row?.StanInfo?.agentAttribute;
      data.openForm.agentId = row?.StanInfo?.agentId;
      data.openForm.agentName = row?.StanInfo?.agentDetail?.agentName;
      data.openForm.terminalPrice = row?.StanInfo?.terminalPrice;
      data.openForm.tradePrice = row?.StanInfo?.tradePrice;
      data.openForm.distributePrice = row?.DevDistributeInfo?.distributePrice;
      data.openForm.computeMode = row?.DevDistributeInfo?.computeMode;
      data.toPath = "businessFlow";
    };

    const cellStyle = () => {
      return "cursor:pointer;";
    };

    const handlSave = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          context.emit("succsess", handlObj());
          handlRemove();
        }
      });
    };

    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          console.log(handlObj(), "---------------");
          context.emit("succsess", handlObj());
          close();
        }
      });
    };

    const handlObj = () => {
      const dataObj = {
        obj: {
          productName: data.openForm.productName,
          producer: data.openForm.producer,
          productId: data.openForm.productId,
          terminalId: data.openForm.terminalId,
          directionNumber: Number(data.openForm.directionNumber),
          directionTime: data.openForm.directionTime,
          batchNumber: data.openForm.batchNumber,
          minSaleUnit: data.openForm.minSaleUnit,
          distributeId: data.openForm.distributeId,
          distributeDetailId: data.openForm.distributeDetailId,
          distributeDetailName: data.openForm.distributeDetailName,
          agentType: data.openForm.agentType,
          agentAttribute: data.openForm.agentAttribute,
          agentId: data.openForm.agentId,
          agentName: data.openForm.agentName,
          terminalPrice: Number(data.openForm.terminalPrice),
          tradePrice: Number(data.openForm.tradePrice),
          distributePrice: Number(data.openForm.distributePrice),
          computeMode: data.openForm.computeMode,
          stanInfoId: data.openForm.stanInfoId,
          terminalName: data.openForm.terminalName,
          terminalType: data.openForm.terminalType,
          productPopularName: data.openForm.productPopularName,
          approvalNumber: data.openForm.approvalNumber,
          packSpecs: data.openForm.packSpecs,
          id: data.openForm.id,
        },
        id: data.openForm.itemTitle ? data.openForm.itemTitle[2] : -1,
        path: data.toPath,
      };

      return dataObj; //JSON.parse(JSON.stringify( dataObj));
    };

    const change = (val) => {
      if (val === null) {
        data.openForm.directionTime = "";
      } else {
        data.openForm.directionTime = val;
      }
    };

    const handleTo = () => {
      data.toPath = "marketing";
      context.emit("succsess", handlObj());
    };

    onMounted(() => {});
    return {
      ...toRefs(data),
      close,
      open,
      handlSubmit,
      handlCurNum,
      handlSave,
      handlRemove,
      querySearchTerminal,
      handleSelecTerminal,
      handlChangeProduct,
      handlObj,
      aloneClick,
      cellStyle,
      disabledDate,
      change,
      handleCreateTerminal,
      handleTo,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
:deep(.el-radio__label) {
  display: none;
}

:deep(.btnss) {
  padding: 0 !important;
}
</style>
